package com.zhihuichongcheng.application.ui.task;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.bean.task.SubTaskBean;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.net.HttpManager;
import com.zhihuichongcheng.application.ui.im.activity.UserListActivity;
import com.zhihuichongcheng.application.util.BroadCastUtils;
import com.zhihuichongcheng.application.util.StringUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * SubTaskDetailActivity
 *
 * Created by LK on 2017/1/17.
 */
public class SubTaskDetailActivity extends BaseActivity
        implements View.OnClickListener, TimePickerDialog.OnTimeSetListener {
    public static final int REQUEST_CODE_CHOOSE_USER = 1000;
    public static final String EXTRA_TASK_ID = "extra_task_id";
    public static final String EXTRA_SUB_TASK_ID = "extra_sub_task_id";
    protected HttpManager manager;
    private EditText mInputTitle;
    private TextView mTvUsers, mTvFinishTime;
    private SubTaskBean currentSubTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentSubTask = new SubTaskBean();
        if (null != getIntent().getExtras()) {
            Bundle bundle = getIntent().getExtras();
            if (bundle.containsKey(EXTRA_SUB_TASK_ID)) {
                currentSubTask.setSubTaskId(bundle.getInt(EXTRA_SUB_TASK_ID));
            }
            if (bundle.containsKey(EXTRA_TASK_ID)) {
                currentSubTask.setUserMissionId(bundle.getInt(EXTRA_TASK_ID));
            } else {
                finish();
            }

        }

        manager = HttpManager.getInstance(this);

        setContentView(R.layout.activity_sub_task);
        initView();
    }

    private void initView() {
        setTitle("子任务详情");
        getTvArrowTitle().setVisibility(View.INVISIBLE);
        mInputTitle = (EditText) this.findViewById(R.id.input_title);
        mTvUsers = (TextView) findViewById(R.id.tv_sub_task_user);
        mTvFinishTime = (TextView) findViewById(R.id.tv_sub_task_time);
        findViewById(R.id.ll_sub_task_executors).setOnClickListener(this);
        findViewById(R.id.ll_sub_task_time).setOnClickListener(this);

        if (!isCreateTask()) {
            loadData();
        } else {
            setTvRight("保存", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String checkResult = checkItems();
                    if (StringUtil.isEmpty(checkResult))
                        save();
                    else
                        ToastOpt.createToast(getContext(), checkResult);
                }
            });
        }
    }

    private boolean isCreateTask() {
        return currentSubTask.getSubTaskId() <= 0;
    }

    private void loadData() {
        DialogUtil.showLoadDiadlog(getContext());
        HashMap<String, String> params = new HashMap<>();
        params.put("subtaskId", currentSubTask.getSubTaskId() + "");
        params.put("token", mUser.getToken());

        manager.post(NetworkAPI.MISSION_SUBTASK_DETAIL, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                currentSubTask = GsonUtil.praseFromStringToBean(value, SubTaskBean.class);
                resetViews();
                if (currentUserIsCreateUser()) {
                    setTvRight("保存", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String checkResult = checkItems();
                            if (StringUtil.isEmpty(checkResult))
                                save();
                            else
                                ToastOpt.createToast(getContext(), checkResult);
                        }
                    });
                }
                mInputTitle.setEnabled(currentUserIsCreateUser() ? true : false);
                findViewById(R.id.ll_sub_task_executors).setClickable(currentUserIsCreateUser() ? true : false);
                findViewById(R.id.ll_sub_task_time).setClickable(currentUserIsCreateUser() ? true : false);

            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), value);
            }
        }, params);
    }

    /**
     * 检查必填项
     */
    private String checkItems() {
        String result = "";
        if (StringUtils.isEmpty(mInputTitle.getText().toString().trim()))
            result = "请输入标题";
        else if (StringUtils.isEmpty(mTvUsers.getText().toString().trim()))
            result = "请设置执行者";
        else if (StringUtils.isEmpty(mTvFinishTime.getText().toString().trim()))
            result = "请设置截止日期";
        return result;
    }

    /**
     * 保存任务
     */
    private void save() {
        DialogUtil.showLoadDiadlog(getContext());
        HashMap<String, String> params = new HashMap<>();
        if (currentSubTask.getSubTaskId() > 0) {
            params.put("subtaskId", currentSubTask.getSubTaskId() + "");
        }
        params.put("userMissionId", currentSubTask.getTaskId() + "");
        params.put("title", mInputTitle.getText().toString().trim());
        params.put("receiveUserId", currentSubTask.getExecutorUserIds());
        params.put("finishTime", currentSubTask.getFinishTimeFormat());
        params.put("token", mUser.getToken());

        manager.post(NetworkAPI.MISSION_SUBTASK_PUBLISH, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code != 2) {
                    BroadCastUtils.getInstance().actionRefreshSubTaskList(SubTaskDetailActivity.this);
                    finish();
                } else {
                    ToastOpt.createToast(getContext(), msg);
                }
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), "发布失败 " + value);
            }
        }, params);
    }

    /**
     * 设置View的状态
     */
    private void resetViews() {
        mInputTitle.setText(currentSubTask.getTitle());
        mTvUsers.setText(currentSubTask.getExecutorNicknames());
        mTvFinishTime.setText(currentSubTask.getFinishTimeToShow());
    }

    private boolean currentUserIsCreateUser() {
        return currentSubTask.getUserId() == Integer.parseInt(app.getUser().getUserId());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_sub_task_executors:
                Bundle bundleExecutor = new Bundle();
                bundleExecutor.putString(UserListActivity.EXTRA_TITLE, "执行者");
                bundleExecutor.putBoolean(UserListActivity.EXTRA_FOR_RESULT, true);
                startActivityForResult(UserListActivity.class,
                        REQUEST_CODE_CHOOSE_USER,
                        bundleExecutor);
                break;
            case R.id.ll_sub_task_time:
                DialogUtil.showDatePick(getContext(), new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        String[] date = s.split("-");
                        String year = date[0];
                        String month = date[1];
                        String day = date[2];
                        String finishTime = year + "年" + month + "月" + day + "日" + " 23:59:59";
                        currentSubTask.setFinishTime(finishTime);
                        showSelectTimeDialog();
                    }
                });
                break;
        }
    }

    private void showSelectTimeDialog() {
        Calendar time = Calendar.getInstance();
        TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(
                this,
                time.get(Calendar.HOUR_OF_DAY),
                time.get(Calendar.MINUTE),
                true);
        timePickerDialog.show(getFragmentManager(), "TimePickerDialog");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_USER) {
            if (resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
                List<UserBean> result = data.getParcelableArrayListExtra(UserListActivity.EXTRA_RESULT_USERS);
                currentSubTask.setReceiveUsers(result);
                mTvUsers.setText(currentSubTask.getExecutorNicknames());
            }
        }

    }

    @Override
    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
        String time = " " + hourOfDay + ":" + minute + "截止";
        String[] items = currentSubTask.getFinishTime().split(" ");
        currentSubTask.setFinishTime(items[0] + time);
        mTvFinishTime.setText(currentSubTask.getFinishTime());
    }
}
